package fun.boomcat.luckyhe.mirai.plugin.bilibilivideoinfoautogenerator.listener;

import fun.boomcat.luckyhe.mirai.plugin.bilibilivideoinfoautogenerator.utils.BilibiliUtil;
import fun.boomcat.luckyhe.mirai.plugin.bilibilivideoinfoautogenerator.utils.entity.BilibiliSubjectObject;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.ListenerHost;
import net.mamoe.mirai.event.events.MessageEvent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BilibiliMessageListener implements ListenerHost {
    @EventHandler
    public void onMessageEvent(MessageEvent event) throws IOException {
        String message = event.getMessage().contentToString();
        Contact subject = event.getSubject();

        String regex = "((?i)bv)\\w+";
        Matcher m = Pattern.compile(regex).matcher(message);
        List<String> checkBVList = new ArrayList<>();
        while (m.find()) {
            String bv = m.group();
            if (checkBVList.contains(bv)) {
                continue;
            } else {
                checkBVList.add(bv);
            }
        }

        regex = "(?<=((?i)av))\\d+";
        m = Pattern.compile(regex).matcher(message);
        List<Long> checkAVList = new ArrayList<>();
        while (m.find()) {
            long av = Long.parseLong(m.group());
            if (checkAVList.contains(av)) {
                continue;
            } else {
                checkAVList.add(av);
            }
        }

        regex = "(?<=((?i)uid))\\d+";
        m = Pattern.compile(regex).matcher(message);
        List<Long> checkUserList = new ArrayList<>();
        while (m.find()) {
            long uid = Long.parseLong(m.group());
            if (checkUserList.contains(uid)) {
                continue;
            } else {
                checkUserList.add(uid);
            }
        }

        int totalCount = checkAVList.size() + checkBVList.size() + checkUserList.size();
        if (totalCount > 5) {
            subject.sendMessage("太多了，不干！最多五个av或bv或uid号！");
            return;
        }

        for (String bv : checkBVList) {
            BilibiliUtil.addQueue(new BilibiliSubjectObject(subject, null, bv, null, event.getBot()));
        }

        for (long av : checkAVList) {
            BilibiliUtil.addQueue(new BilibiliSubjectObject(subject, av, null, null, event.getBot()));
        }

        for (long uid : checkUserList) {
            BilibiliUtil.addQueue(new BilibiliSubjectObject(subject, null, null, uid, event.getBot()));
        }
    }
}
